<!--
 * @Date: 2022-02-28 14:06:24
 * @Author: 陶子
 * @LastEditTime: 2023-06-12 17:37:55
 * @FilePath: \jk_one-stop_pc\src\views\workManagement\reportRecord\buildRecord.vue
 * @pageName: 这是--(新建报工)--页面
-->
<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['生产管理', '报工记录']" currentMenu="报工"></crumbs>
    <div class="form-body">
      <a-card title="工序信息" :bordered="false" style="margin-top: 12px">
        <a-form-model ref="ruleFormOne" :model="buildForm" :rules="rules">
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="工单编号" style="width: 100%" prop="orderId">
                <a-input
                  @click="openIt"
                  v-model="buildForm.orderCode"
                  placeholder="请选择"
                  :read-only="true"
                  :disabled="isEdit"
                  :class="buildForm.orderCode ? 'has-value' : ''"
                >
                  <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                  <a-icon
                    slot="suffix"
                    type="close-circle"
                    theme="filled"
                    class="close-icon"
                    v-if="!isEdit"
                    @click="getSelectValue(false, '', [])"
                  />
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="生产产品" style="width: 100%">
                <a-input v-model="buildForm.showProductName" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="规格" style="width: 100%">
                <a-input v-model="buildForm.goodsSpec" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="工序" style="width: 100%" prop="taskId">
                <a-select
                  v-model="buildForm.taskId"
                  class="row-input"
                  allowClear
                  placeholder="请选择"
                  :disabled="isEdit"
                  @change="taskIdChange"
                >
                  <a-select-option :value="item.id" v-for="item in taskList" :key="item.id">
                    {{ item.processCode }}-{{ item.processName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="基本单位" style="width: 100%">
                <a-input v-model="buildForm.goodsBasicUnitText" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="可报工数" style="width: 100%">
                <a-input v-model="buildForm.availableNumForReport" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="报工单位" style="width: 100%">
                <a-input v-model="buildForm.processWorkUnitText" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="工序进度" style="width: 100%">
                <a-input v-model="buildForm.showReport" disabled placeholder="-" />
                <div class="havePadding">
                  <a-progress
                    :percent="Number(buildForm.completePercent)"
                    :strokeWidth="5"
                    :showInfo="false"
                    :strokeColor="checkColor(buildForm.completePercent)"
                  />
                  <span>{{ buildForm.completePercent }}%</span>
                </div>
                <a-tooltip class="code-btn">
                  <template slot="title"> 当前工序报工总数/生产计划数（报工单位） </template>
                  <a-icon type="question-circle" theme="filled" style="color: rgba(170, 170, 170, 0.8)" />
                </a-tooltip>
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="计划时间" style="width: 100%">
                <a-input v-model="buildForm.planTime" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="设备" style="width: 100%">
                <a-input v-model="buildForm.deviceName" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="工序要求" style="width: 100%">
                <a-input v-model="buildForm.processRequire" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <a-card title="操作报工" :bordered="false" style="margin-top: 12px">
        <a-form-model ref="ruleFormTwo" :model="buildForm" :rules="rules">
          <a-row>
             <a-col :span="7">
              <a-form-model-item label="批次编号" style='width:100%' prop='batchId'>
                <a-select :disabled="isEdit" @change="changeBatch" v-model="buildForm.batchId" allowClear class="row-input" placeholder="请选择">
                  <a-select-option :value="item.batchId" v-for="item in batchList" :key="item.batchId">
                    {{item.batchCode}}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="操作人" style="width: 100%" prop="operatorId">
                <a-select @change="changeUser" mode="multiple" allowClear v-model="selectUser" class="row-input" placeholder="请选择">
                  <a-select-option :value="item.value" v-for="item in operatorList" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="报工数" style="width: 100%" prop="reportWorkNum">
                <a-input v-model="buildForm.reportWorkNum" disabled placeholder="-" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="合格数" style="width: 100%">
                <a-input
                  v-model="buildForm.qualifiedNum"
                  :disabled="isEdit"
                  @blur="checkValue('qualifiedNum', buildForm.qualifiedNum)"
                  @input="formatInput('qualifiedNum', buildForm.qualifiedNum)"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-model-item label="不合格数" style="width: 100%">
                <a-input
                  readOnly @click="showModel"
                  :disabled="isEdit"
                  v-model="buildForm.notQualifiedNum"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="不合格原因" style="width: 100%">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ buildForm.notQualifiedReasonText || '请输入不合格数' }}</span>
                  </template>
                  <span><a-input v-model="buildForm.notQualifiedReasonText" disabled placeholder="请输入" /></span>
                </a-tooltip>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form-model ref="ruleFormThree" :model="buildForm">
          <a-form-model-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" v-model="buildForm.remark" />
          </a-form-model-item>
          <a-form-model-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
          </a-form-model-item>
        </a-form-model>
      </a-card>
      <div style="margin-top: 12px">
        <Examine @submitProcess="submitProcess" :type="isEdit ? '1' : '0'" id="MESS_TASK_REPORT_WORK_APPLY_FOR_PRODUCT" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>
    <div
      class="footer-submit form-footer"
    >
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button @click="submitProcess" type="primary" :loading="subLoading" class="submitBtn"> 提交 </a-button>
    </div>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue" :key="indexNumber" @cancel="searchResetNumber">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="工单编号">
              <a-input v-model="filterForm.orderCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="产品名称">
              <a-input v-model="filterForm.goodsName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchNumber()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetNumber">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
    <a-modal
      title="不合格数输入"
      :visible="notQualifiedTable.visible"
      :confirm-loading="notQualifiedTable.confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-table :columns="notQualifiedTable.columns" :data-source="notQualifiedTable.dataSource" :pagination="false">
        <span slot="notQualifiedNum" slot-scope="text, record, index">
          <a-input v-model="notQualifiedTable.dataSource[index].notQualifiedNum" @input='(e) => inputNQNum(e, index)' placeholder="请输入" />
        </span>
      </a-table>
      <template slot="footer">
        <span style="float: left;line-height:33px">不合格原因：{{ notQualifiedTable.reasonNum }} 不合格数：{{ notQualifiedTable.num }}</span>
        <a-button key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="handleOk">
          确定
        </a-button>
      </template>
    </a-modal>
  </jke-modal>
</template>
<script>
import { ajaxGetDictItems } from '@/api/api'
import { clearNoNum, accAdd, accSub } from '@/utils/util'
import Examine from '@/components/examine'
import tableSelect from '@/components/tableSelect'
import { mapState } from 'vuex'
import {
  getOrderCodeDict,
  getProcessOptions,
  taskDetailApi,
  getReportTeamUserListByTaskId,
  recordAdd,
  queryBatchTaskReportList,
  messTaskReportWorkApplyEdit,
  recordDetailApi
} from '@/api/productOrder'
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
export default {
  data() {
    return {
      jkeForm: {
        title: '报工',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexNumber: 0,
      columns: [
        {
          title: '工单编号',
          ellipsis: true,
          width: 180,
          dataIndex: 'orderCode',
        },
        {
          title: '产品名称',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsName',
        },
        {
          title: '规格',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsSpec',
        },
        {
          title: '基本单位',
          dataIndex: 'goodsBasicUnitText',
          ellipsis: true,
          width: 90,
        },
      ],
      numberValue: '',
      numberText: '',
      filterForm: {
        orderCode: '', //工单编号
        goodsName: '', //产品名称
      },
      //下拉改弹窗结束
      subLoading: false,
      buildForm: {
        orderCode: '', //工单编号
        orderId: undefined,
        showProductName: '',
        goodsSpec: '',
        goodsBasicUnitText: '',
        taskId: '',
        availableNumForReport: '',
        excessCanReportNum: '',
        processWorkUnitText: '',
        planTime: '',
        deviceName: '',
        processRequire: '',
        showReport: '',
        completePercent: '',
        operatorId: '',
        reportWorkNum: '',
        qualifiedNum: '',
        notQualifiedNum: '',
        remark: '',
        notQualifiedReason: '',
        notQualifiedReasonText: '',
      },
      rules: {
        orderId: [{ required: true, message: '请选择', trigger: 'change' }],
        taskId: [{ required: true, message: '请选择', trigger: 'change' }],
        operatorId: [{ required: true, message: '请选择', trigger: 'change' }],
        reportWorkNum: [{ required: true, message: '请输入合格数或不合格数', trigger: 'blur' }],
      },
      workOrderList: [],
      taskList: [],
      operatorList: [],
      //分割线
      attachment: '', //附件
      // 辅助单位
      dictOptions: [],
      currentLoginUser: {},
      selectUser: undefined,
      notQualifiedTable: {
        visible: false,
        confirmLoading: false,
        reasonNum: 0,
        num: 0,
        dataSource: [],
        currentData: [],
        columns: [
          {
            title: '不合格原因',
            dataIndex: 'notQualifiedReasonText',
            ellipsis: true,
            width: '40%',
          },
          {
            title: '不合格数',
            dataIndex: 'notQualifiedNum',
            ellipsis: true,
            width: '50%',
            scopedSlots: { customRender: 'notQualifiedNum' },
          },
        ]
      },
      batchList: [],
      defaultNQTable: [],
      availableNumForReport: '',
      excessCanReportNum: '',
      qualifiedNumByUser: false,
      orderByBatch: true, // 默认工单工序由批次带出，选定工单时改为false
      taskByBatch: false,
      isEdit: false,
    }
  },
  components: {
    FileUpload,
    crumbs,
    Examine,
    tableSelect,
  },
  mounted() {},
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
  },
  methods: {
    initForm(id) {
      this.$store.commit('SET_CURRENT_PREFIX','/jksaas-produce/produce')
      Object.assign(this.$data, this.$options.data.call(this));
      this.jkeForm.visible = true
      this.currentLoginUser = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
      ajaxGetDictItems('mess_not_qualified_reason', null).then((res) => {
        if (res.result) {
          this.notQualifiedTable.dataSource = res.result.map((item) => {
            let obj = {
              notQualifiedReasonText: item.text,
              notQualifiedReason: item.value,
              notQualifiedNum: ''
            }
            return obj
          })
          this.notQualifiedTable.currentData = this.notQualifiedTable.dataSource
          this.defaultNQTable = this.notQualifiedTable.dataSource
        }
      })
      this.getInitData(id)
    },
    showModel() {
      this.notQualifiedTable.dataSource = JSON.parse(JSON.stringify(this.notQualifiedTable.currentData))
      let num = 0
      let reasonNum = 0
      for (let i = 0; i < this.notQualifiedTable.dataSource.length; i++) {
        const item = this.notQualifiedTable.dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          reasonNum += Number(item.notQualifiedNum) > 0 ? 1 : 0
        }
      }
      this.notQualifiedTable.num = num
      this.notQualifiedTable.reasonNum = reasonNum
      this.notQualifiedTable.visible = true
    },
    handleOk() {
      let reasons = []
      let reasonTexts = []
      let num = 0
      for (let i = 0; i < this.notQualifiedTable.dataSource.length; i++) {
        const item = this.notQualifiedTable.dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          if (Number(item.notQualifiedNum) > 0) {
            reasons.push(`${item.notQualifiedReason}:${item.notQualifiedNum}`)
            reasonTexts.push(`${item.notQualifiedReasonText}:${item.notQualifiedNum}`)
          }
        }
      }
      this.notQualifiedTable.currentData = JSON.parse(JSON.stringify(this.notQualifiedTable.dataSource))
      this.buildForm.notQualifiedReason = reasons.join(',')
      this.buildForm.notQualifiedReasonText = reasonTexts.join(',')
      this.buildForm.notQualifiedNum = num
      this.checkValue("notQualifiedNum",num)
      this.notQualifiedTable.visible = false
    },
    handleCancel() {
      this.notQualifiedTable.visible = false
    },
    inputNQNum(e, index) {
      let num = 0
      let reasonNum = 0
      this.notQualifiedTable.dataSource[index].notQualifiedNum = clearNoNum(e.target.value)
      for (let i = 0; i < this.notQualifiedTable.dataSource.length; i++) {
        const item = this.notQualifiedTable.dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          reasonNum += Number(item.notQualifiedNum) > 0 ? 1 : 0
        }
      }
      this.notQualifiedTable.num = num
      this.notQualifiedTable.reasonNum = reasonNum
    },
    changeUser(v) {
      this.buildForm.operatorId = v.join(',')
    },
    // 编号下拉改弹窗
    openIt() {
      let par = {
        list: '/mess/messProductOrder/getOrderCodeDict?status=inProduction&type=production',
        visible: true, //弹窗开启
        title: '编号', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.numberValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.numberText, //回显的中文，如：'张三'
        textKey: 'orderCode', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    getSelectValue(id, text, item) {
      this.batchList = []
      this.buildForm.batchId = ''
      if (!id) {
        this.getBatch({type:'production'})
        this.orderByBatch = true
        this.taskByBatch = false
        // 重置选编号带出的值
        this.buildForm.showProductName = ''
        this.buildForm.goodsSpec = ''
        this.buildForm.goodsBasicUnitText = ''
        this.buildForm.orderId = ''
        this.buildForm.orderCode = ''
        // 重置选工序带出的值
        this.buildForm.availableNumForReport = ''
        this.buildForm.excessCanReportNum = ''
        this.buildForm.qualifiedNum = ''
        this.buildForm.processWorkUnitText = ''
        this.buildForm.planTime = ''
        this.buildForm.deviceName = ''
        this.buildForm.processRequire = ''
        this.buildForm.showReport = ''
        this.buildForm.completePercent = ''
        this.buildForm.taskId = ''
        // 重置组件中选的值
        this.numberText = ''
        this.numberValue = ''
        // 重置工序列表
        this.taskList = []
        return
      }
      this.indexNumber += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.numberValue = id
      this.numberText = text
      this.orderCodeChange(id)
    },
    searchResetNumber() {
      this.filterForm.orderCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchNumber() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    checkColor(value) {
      if (value == 0) {
        return '#DFDFDF'
      } else if (value >= 100) {
        return '#00B042'
      } else {
        return '#1890FF'
      }
    },
    formatInput(type, value) {
      this.buildForm[type] = clearNoNum(value)
    },
    checkValue(type, value) {
      if (type == 'qualifiedNum') {
        if (Number(value) != Number(this.availableNumForReport)) {
          this.qualifiedNumByUser = true
        }
        let num = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(this.buildForm.notQualifiedNum ? this.buildForm.notQualifiedNum : 0)
        )
        if (Number(value) > Number(num)) {
          this.buildForm[type] = ''
          this.buildForm.reportWorkNum = this.buildForm.notQualifiedNum
          this.$antdMessage.warning('报工总数不能大于最大应生产数！')
        } else {
          if (this.buildForm.notQualifiedNum) {
            this.buildForm.reportWorkNum = accAdd(
              Number(this.buildForm.notQualifiedNum),
              Number(this.buildForm.qualifiedNum)
            )
          } else {
            this.buildForm.reportWorkNum = this.buildForm.qualifiedNum
          }
          this.$refs['ruleFormTwo'].validateField(['reportWorkNum'])
        }
      } else {
        let num = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(this.buildForm.qualifiedNum ? this.buildForm.qualifiedNum : 0)
        );
        let qnum = accSub(
          Number(this.buildForm.excessCanReportNum),
          Number(value)
        );
        if (Number(value) > Number(num)) {
          if (!this.qualifiedNumByUser) {
            this.buildForm.qualifiedNum = Number(qnum) > 0 ? qnum : 0
          }
          let report = accAdd(
            Number(value),
            Number(this.buildForm.qualifiedNum)
          )
          this.buildForm.reportWorkNum = report > this.buildForm.excessCanReportNum ? '' : report
          if (report > this.buildForm.excessCanReportNum) {
            this.notQualifiedTable.reasonNum = 0
            this.notQualifiedTable.num = 0
            this.notQualifiedTable.dataSource = JSON.parse(JSON.stringify(this.defaultNQTable))
            this.notQualifiedTable.currentData = JSON.parse(JSON.stringify(this.defaultNQTable))
            this.buildForm.notQualifiedNum = ''
            this.buildForm.notQualifiedReasonText = ''
            this.buildForm.notQualifiedReason = ''
            this.$antdMessage.warning('报工总数不能大于最大应生产数！')
            return
          }
        } else {
          if (this.buildForm.qualifiedNum) {
            this.buildForm.reportWorkNum = accAdd(
              Number(this.buildForm.notQualifiedNum),
              Number(this.buildForm.qualifiedNum)
            );
          } else {
            this.buildForm.reportWorkNum = this.buildForm.notQualifiedNum;
          }
        }
        this.$refs['ruleFormTwo'].validateField(['reportWorkNum'])
      }
    },
    taskListByOrder() {
      let obj = {
        orderId: this.buildForm.orderId,
        reportStatus: 'yes',
        type: 'production',
      }
      getProcessOptions(obj).then((res) => {
        if (res.success) {
          this.taskList = res.result
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    taskIdChange(value) {
      this.clearFormText()
      let batchObj = {orderId: this.buildForm.orderId, taskId: this.buildForm.taskId, type:'production'}
      if (!this.orderByBatch && !this.taskByBatch) {
        this.getBatch(batchObj, value)
        // this.taskByBatch = false
      }
      if (!value) {
        this.buildForm.availableNumForReport = ''
        this.buildForm.excessCanReportNum = ''
        this.buildForm.qualifiedNum = ''
        this.buildForm.processWorkUnitText = ''
        this.buildForm.planTime = ''
        this.buildForm.deviceName = ''
        this.buildForm.processRequire = ''
        this.buildForm.showReport = ''
        this.buildForm.completePercent = ''
        if (!this.orderByBatch) {
          // 删除工序-如果工序不是批次带出则根据工单重置批次和工序
          this.getBatch(batchObj)
          this.buildForm.batchId = undefined
          this.taskListByOrder()
        }
        return
      }
      let obj = {
        id: value,
      }
      taskDetailApi(obj).then((res) => {
        if (res.success) {
          let item = res.result

          this.availableNumForReport = item.availableNumForReport
          this.excessCanReportNum = item.excessCanReportNum
          
          this.buildForm.processWorkUnitText = item.processWorkUnitText
          this.buildForm.planTime = item.planStartTime + '~' + item.planEndTime
          this.buildForm.deviceName = item.deviceName
          this.buildForm.processRequire = item.processRequire
          this.buildForm.showReport = item.reportNum + '/' + item.taskPlanNum
          this.buildForm.completePercent = item.completePercent
          if (this.buildForm.batchId) {
            queryBatchTaskReportList(obj).then(res => {
              let openList = res.result
              let tasks = openList.find(bat => bat.batchId == this.buildForm.batchId)
              let task = {}
              if (tasks.batchTaskList.length > 0) {
                task = tasks.batchTaskList.find(tb => tb.taskId == value)
              }
              this.checkBatchWithTask(task)
            })
          } else {
            this.buildForm.availableNumForReport = item.availableNumForReport
            this.buildForm.excessCanReportNum = item.excessCanReportNum
            this.buildForm.qualifiedNum = item.availableNumForReport
          }
          
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
      this.buildForm.operatorId = ''
      this.selectUser = undefined
      this.operatorList = []
      this.buildForm.reportWorkNum = ''
      this.buildForm.notQualifiedNum = ''
      this.buildForm.notQualifiedReason = ''
      this.buildForm.notQualifiedReasonText = ''
      let taskObj = {
        taskId: this.buildForm.taskId,
      }
      getReportTeamUserListByTaskId(taskObj).then((res) => {
        if (res.success) {
          this.operatorList = res.result
          for (let item of this.operatorList) {
            if (item.value == this.currentLoginUser.id) {
              this.buildForm.operatorId = item.value
              this.selectUser = [item.value]
            }
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    orderCodeChange(value) {
      for (let item of this.workOrderList) {
        if (item.id == value) {
          this.buildForm.showProductName = item.goodsCode + '-' + item.goodsName
          this.buildForm.goodsSpec = item.goodsSpec
          this.buildForm.goodsBasicUnitText = item.goodsBasicUnitText
          this.buildForm.orderId = item.id
          this.orderByBatch = false
          this.buildForm.orderCode = item.orderCode
          this.$refs['ruleFormOne'].validateField(['orderId'])
        }
      }
      let batchObj = {orderId: this.buildForm.orderId, taskId: this.buildForm.taskId, type:'production'}
      this.getBatch(batchObj)
      this.taskList = []
      this.buildForm.taskId = ''
      this.buildForm.availableNumForReport = ''
      this.buildForm.excessCanReportNum = ''
      this.buildForm.processWorkUnitText = ''
      this.buildForm.planTime = ''
      this.buildForm.deviceName = ''
      this.buildForm.processRequire = ''
      this.buildForm.showReport = ''
      this.buildForm.completePercent = ''
      this.buildForm.operatorId = ''
      this.selectUser = undefined
      this.operatorList = []
      this.buildForm.reportWorkNum = ''
      this.buildForm.qualifiedNum = ''
      this.buildForm.notQualifiedNum = ''
      this.buildForm.notQualifiedReason = ''
      this.buildForm.notQualifiedReasonText = ''
      this.taskListByOrder()
    },

    //页面加载请求数据
    getInitData(id) {
      let obj = {
        status: 'inProduction',
        type: 'production',
      }
      getOrderCodeDict(obj).then((res) => {
        if (res.success) {
          this.workOrderList = res.result
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
      if (id) {
        this.isEdit = true
        recordDetailApi({id: id}).then((res) => {
          if (res.success) {
            if (res.result) {
              let taskDetail = res.result.taskDetail
              let item = res.result
              this.buildForm.orderCode = taskDetail.orderCode
              this.buildForm.showProductName = taskDetail.goodsCode + '-' + taskDetail.goodsName
              this.buildForm.goodsSpec = taskDetail.goodsSpec
              this.buildForm.goodsBasicUnitText = taskDetail.goodsBasicUnitText
              this.buildForm.taskId = taskDetail.processName
              this.buildForm.availableNumForReport = taskDetail.availableNumForReport
              this.buildForm.processWorkUnitText = taskDetail.processWorkUnitText
              this.buildForm.showReport = taskDetail.reportNum + '/' + taskDetail.taskPlanNum
              this.buildForm.completePercent = taskDetail.completePercent
              this.buildForm.planTime = taskDetail.planStartTime + '~' + taskDetail.planEndTime
              this.buildForm.deviceName = taskDetail.deviceName || '-'
              this.buildForm.processRequire = taskDetail.processRequire || '-'
              this.buildForm.batchId = item.batchCode
              this.selectUser = [item.operatorId]
              this.buildForm.operatorId = item.operatorId
              this.buildForm.qualifiedNum = item.qualifiedNum
              this.buildForm.reportWorkNum = item.reportWorkNum
              this.buildForm.notQualifiedNum = item.notQualifiedNum
              this.buildForm.notQualifiedReasonText = item.notQualifiedReason
              this.buildForm.remark = item.remark
              this.buildForm.id = item.id
              this.attachment = item.attachment
              getReportTeamUserListByTaskId({taskId: taskDetail.id}).then((res) => {
                if (res.success) {
                  if (res.result&&res.result.length>0) {
                    this.operatorList = res.result
                    let operArr = this.buildForm.operatorId.split(',')
                    let oper = []
                    for (let j = 0; j < operArr.length; j++) {
                      const oj = operArr[j];
                      for (let k = 0; k < res.result.length; k++) {
                        const ok = res.result[k];
                        if (ok.value == oj) {
                          oper.push(oj)
                        }
                      }
                    }
                    if (oper.length === 0) {
                      this.buildForm.operatorId = ''
                      this.selectUser = undefined
                    } else {
                      this.buildForm.operatorId = oper.join(',')
                      this.selectUser = oper
                    }
                  } else {
                    this.buildForm.operatorId = ''
                    this.selectUser = undefined
                  }
                } else {
                  this.$antdMessage.warning(res.message)
                }
              })
            }
          } else {
            this.$antdMessage.warning(res.message)
          }
        })
      } else {
        this.getBatch({type:'production'})
      }
    },
    // 批次编号列表
    getBatch(obj, task) {
      queryBatchTaskReportList(obj).then(res => {
        console.log('批次编号:',res);
        this.batchList = res.result || []
        if (task&&this.buildForm.batchId) { // 如果工序不是批次带出，切换工序时查看是否已选批次，已选批次的话，若新工序下有该批次则不用删除批次
          let bat = this.batchList.find(b=> b.id == this.buildForm.batchId)
          if (bat) {
            return
          }
        }
        this.buildForm.batchId = ''
      })
    },
    // 选择批次
    changeBatch(v, row) {
      this.qualifiedNumByUser = false
      if (v) {
        let tasks = this.batchList.find(item => item.batchId == v)
        this.buildForm.batchCode = tasks.batchCode
        let task = {}
        if (tasks.batchTaskList.length > 0) {
          task = tasks.batchTaskList[0]
        }
        let { taskId, orderId} = this.buildForm
        if (this.orderByBatch) {
          // 工单信息回显begin
          console.log('开始回显工单');
          for (let item of this.workOrderList) {
            console.log('开始回显工单-列表里有吗？');
            if (item.id == task.orderId) {
              console.log('开始回显工单-列表里有');
              this.buildForm.showProductName = item.goodsCode + '-' + item.goodsName
              this.buildForm.goodsSpec = item.goodsSpec
              this.buildForm.goodsBasicUnitText = item.goodsBasicUnitText
              this.buildForm.orderId = item.id
              this.buildForm.orderCode = item.orderCode
              this.$refs['ruleFormOne'].validateField(['orderId'])
              this.indexNumber += 1
              this.numberValue = item.id
              this.numberText = item.goodsCode + '-' + item.goodsName
            }
          }
          // 工单信息回显end
        }
        if (!taskId&&!orderId) { // 无工单且无工序
          this.clearFormText()
          // 工序信息回显begin
          this.setTaskInfoByBatch(task, tasks)
          // 工序信息回显end
        } else if (!taskId&&orderId) { // 有工单，无工序
          this.clearFormText()
          this.setTaskInfoByBatch(task, tasks)
          console.log('有工单无工序');
        } else if (taskId&&orderId) {
          this.buildForm.reportWorkNum = ''
          this.buildForm.notQualifiedNum = ''
          this.buildForm.notQualifiedReason = ''
          this.buildForm.notQualifiedReasonText = ''
          this.notQualifiedTable.reasonNum = 0
          this.notQualifiedTable.num = 0
          this.notQualifiedTable.dataSource = JSON.parse(JSON.stringify(this.defaultNQTable))
          this.notQualifiedTable.currentData = JSON.parse(JSON.stringify(this.defaultNQTable))
          if (this.orderByBatch || this.taskByBatch) {
            this.setTaskInfoByBatch(task, tasks)
          } else {
            this.checkBatchWithTask(task)
          }
        }
      } else {
        if (!this.orderByBatch) {
          // 删除批次-如果工序不是批次带出的，需要根据工单重置工序列表
          this.taskListByOrder()
        }
        this.notQualifiedTable.reasonNum = 0
        this.notQualifiedTable.num = 0
        this.notQualifiedTable.dataSource = JSON.parse(JSON.stringify(this.defaultNQTable))
        this.notQualifiedTable.currentData = JSON.parse(JSON.stringify(this.defaultNQTable))
        this.buildForm.notQualifiedNum = ''
        this.buildForm.notQualifiedReasonText = ''
        this.buildForm.notQualifiedReason = ''
        this.buildForm.availableNumForReport = this.availableNumForReport
        this.buildForm.excessCanReportNum = this.excessCanReportNum
        this.buildForm.qualifiedNum = this.availableNumForReport
        this.buildForm.batchCode = ''
      }
    },
    clearFormText() {
      this.buildForm.operatorId = ''
      this.selectUser = undefined
      this.operatorList = []
      this.buildForm.reportWorkNum = ''
      this.buildForm.notQualifiedNum = ''
      this.buildForm.notQualifiedReason = ''
      this.buildForm.notQualifiedReasonText = ''
      this.notQualifiedTable.reasonNum = 0
      this.notQualifiedTable.num = 0
      this.notQualifiedTable.dataSource = JSON.parse(JSON.stringify(this.defaultNQTable))
      this.notQualifiedTable.currentData = JSON.parse(JSON.stringify(this.defaultNQTable))
    },
    checkBatchWithTask(task) {
      if (task.availableNumForReport <= this.availableNumForReport) {
        this.buildForm.availableNumForReport = task.availableNumForReport > 0 ? task.availableNumForReport : ''
        this.buildForm.excessCanReportNum = task.excessCanReportNum
        this.buildForm.qualifiedNum = task.availableNumForReport
      } else if (task.availableNumForReport > this.availableNumForReport) {
        this.buildForm.availableNumForReport = this.availableNumForReport
        this.buildForm.excessCanReportNum = this.excessCanReportNum
        this.buildForm.qualifiedNum = this.availableNumForReport
      }
    },
    setTaskInfoByBatch(task, tasks) {
      this.buildForm.taskId = task.taskId
      this.taskByBatch = true
      this.$refs['ruleFormOne'].validateField(['taskId'])
      this.taskList = tasks.batchTaskList.map((ta) => {
        ta.id = ta.taskId
        return ta
      })
      this.$refs['ruleFormOne'].validateField(['taskId'])
      this.buildForm.availableNumForReport = task.availableNumForReport
      this.buildForm.excessCanReportNum = task.excessCanReportNum
      this.buildForm.qualifiedNum = task.availableNumForReport
      taskDetailApi({id: task.taskId}).then((res) => {
        if (res.success) {
          let item = res.result

          this.availableNumForReport = item.availableNumForReport
          this.excessCanReportNum = item.excessCanReportNum

          this.buildForm.processWorkUnitText = item.processWorkUnitText
          this.buildForm.planTime = item.planStartTime + '~' + item.planEndTime
          this.buildForm.deviceName = item.deviceName
          this.buildForm.processRequire = item.processRequire
          this.buildForm.showReport = item.reportNum + '/' + item.taskPlanNum
          this.buildForm.completePercent = item.completePercent
          // 对比批次和工序的可报工数begin
          this.checkBatchWithTask(task)
          // 对比批次和工序的可报工数end
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
      getReportTeamUserListByTaskId({taskId: task.taskId}).then((res) => {
        if (res.success) {
          this.operatorList = res.result
          for (let item of this.operatorList) {
            if (item.value == this.currentLoginUser.id) {
              this.buildForm.operatorId = item.value
              this.selectUser = [item.value]
            }
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.$router.go(-1)
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (this.isEdit) {
        this.$refs.ruleFormTwo.validate((valid) => {
          if (valid) {
            console.log('操作报工验证通过')
            this.handleSubmit()
          } else {
            return false
          }
        })
        return
      }
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.submitForm(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // 提交
    submitForm(processDataVo) {
      this.$refs.ruleFormOne.validate((valid) => {
        if (valid) {
          console.log('工序信息验证通过')
          this.$refs.ruleFormTwo.validate((valid) => {
            if (valid) {
              console.log('操作报工验证通过')
              this.handleSubmit(processDataVo)
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    },
    handleSubmit(processDataVo) {
      // if (this.buildForm.notQualifiedNum > 0 && this.notQualifiedReason.length == 0) {
      //   this.$antdMessage.warning('不合格数大于0时，不合格原因必填')
      //   return
      // }
      this.subLoading = true
      let params = {
        ...this.buildForm,
        attachment: this.attachment,
        type: 'production',
        processDataVo: processDataVo,
      }
      if (this.isEdit) {
        messTaskReportWorkApplyEdit({
          type: 'production',
          id: this.buildForm.id,
          remark: this.buildForm.remark,
          operatorId: this.buildForm.operatorId,
          attachment: this.attachment,
        }).then((res) => {
          if (res.success) {
            this.$antdMessage.success('编辑成功')
            this.$emit('refresh')
            this.goBack()
          } else {
            this.$antdMessage.warning(res.message)
          }
          this.subLoading = false
        })
      } else {
        recordAdd(params).then((res) => {
          if (res.success) {
            this.$antdMessage.success('报工成功')
            this.$emit('refresh')
            this.goBack()
          } else {
            this.$antdMessage.warning(res.message)
          }
          this.subLoading = false
        })
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.flexBox {
  .flex(flex-start, center);
}
.havePadding {
  .flex(center, center);
  width: 90%;
  font-size: 12px;
  color: #888888;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
// 工艺路线结束
</style>
